<template>
    <div class="page-favourites favourites">
        <div class="user-info-box">
            <van-nav-bar left-arrow @click-left="$router.back(-1)" :fixed="true" :title="$t('m.Favourites')" style="color:#fff;">
                <van-icon name="delete" slot="right" @click="deleteSelected = !deleteSelected"/>
            </van-nav-bar>
            <van-list
                v-model="loading"
                :finished="finished"
                loading-text=" "
                @load="getList"
                class="main-explore">
                <van-checkbox-group v-model="deleteSubmit">
                    <van-cell-group class="f-group">
                <div class="explore-item" @click="checkOrDetail(item.id, index)" v-for="(item, index) in tableData" :key="index"  v-bind:class="[tableData.length % 2 == 0 ? twoClass : oneClass]">

                    <!--<div class="explore-item-icon">-->
                    <!--&lt;!&ndash;<img :src="item.image"  v-lazy="item.image">&ndash;&gt;-->
                    <!--<img v-lazy="item.cover"  :style="defaultImage" alt="" />-->
                    <!--</div>-->
                    <div class="explore-item-icon">
                        <!--<img :src="item.cover" :style="defaultImage" alt=""/>-->
                        <img v-lazy="item.cover" alt="" :key="item.cover" :onload="getWidthAndHeight(item, index)" :class="[item.wth == 1 ? 'width-max' : 'height-max']"/>
                        <div class="sold-status" v-if="item.status == 3">Sold</div>
                    </div>
                    <div class="explore-item-label">{{translateString(item.title)}}</div>
                    <span>
                    <div class="explore-item-label price" v-if="item.priceType == 2">Lks&nbsp;{{regexNum(item.price)}}</div>
                    <div class="explore-item-label price" v-else>Ks&nbsp;{{regexNum(item.price)}}</div>
                    </span>
                    <!--<div class="explore-item-label dates">{{getDateDiff(item.createDatetime)}}</div>-->

                    <van-cell :key="item.favorId" class="f-group-check" v-if="deleteSelected">
                        <van-checkbox :name="item.favorId" ref="checkboxes" />
                    </van-cell>

                    <van-icon name="like" size="28px" class="f-like" />

                </div>
                    </van-cell-group>
                </van-checkbox-group>
            </van-list>
            <van-goods-action v-if="deleteSelected && deleteSubmit.length > 0" class="delete-btn">
                <van-goods-action-big-btn :text="$t('m.Delete')" @click="onClickDelete" primary/>
            </van-goods-action>
            <div class="none" v-if="!loading && tableData.length == 0">
                <img src="../../static/img/images/favourite-none.png" />
                <p>{{$t('m.Nofavouriteyet')}} :)</p>
            </div>
        </div>
        <div style="padding:40px;"></div>
        <footer-bar ref="footer" footerBar="favourites"></footer-bar>
    </div>
</template>
<script>
    import {deleteFavourite, getUserSaveList} from '../../static/api/mgc_api'
    import Qs from 'qs'
    import FooterBar from '@/components/FooterBar'

    export default {
        name: 'Favourites',
        middleware: ['login'],
        components: {
            FooterBar
        },
        data() {
            return {
                defaultImage: {
                    backgroundImage: "url(" + require("../../static/img/images/default-list.png") + ")",
                    backgroundRepeat: "no-repeat",
                    backgroundSize: "100% 100%",
                },
                oneClass: 'one',
                twoClass: 'two',
                deleteSelected: false,
                loading: false,
                finished: false,
                tableData: [],
                pageData: {
                    pageNum: 1,
                    pageSize: 10,
                },
                pageInfo: {
                    totalCount: 0,
                    totalPages: 0
                },
                deleteSubmit: [],
            }
        },
        methods: {
            regexNum(v, len, split) {
                split = split || ',', len = Math.abs((+len) % 20 || 2)
                v = parseFloat((v + '').replace(/[^\d\.-]/g, '')).toFixed(len) + ''
                v = parseFloat(v) + ''
                return v.replace(/\d+/, function (v) {
                        var lit = v.length % 3 == 0
                        var index = lit ? v.length - 3 : -1
                        return v.split('').reverse().join('').replace(/\d{3}/g, function (k, l) {
                            return k + ((l == index && lit) ? '' : split)
                        }).split('').reverse().join('')
                    }
                )
            },
            translateString(str){
                if (!str) return ''
                return this.$translateLang(str, 'unicodeTozawgyi');
            },
            checkOrDetail(id, index) {
                if (this.deleteSelected) {
                    this.$refs.checkboxes[index].toggle();
                } else {
                    this.$router.push({
                        path:'/buydetail',
                        query:{
                            id: id
                        }
                    })
                }

            },
            getDateDiff(dateTimeStamp) {
                if (!dateTimeStamp) return
                let minute = 1000 * 60
                let hour = minute * 60
                let day = hour * 24
                let month = day * 30
                let year = day * 365
                let now = new Date().getTime()
                let diffValue = now - dateTimeStamp
                if (diffValue < 0) return
                let monthC = diffValue / month
                let yearC = diffValue / year
                let weekC = diffValue / (7 * day)
                let dayC = diffValue / day
                let hourC = diffValue / hour
                let minC = diffValue / minute
                let result = ''
                if (yearC >= 1) {
                    if (parseInt(yearC) > 1) {
                        result = "" + parseInt(yearC) + " years ago"
                    } else {
                        result = "" + parseInt(yearC) + " year ago"
                    }
                } else if (monthC >= 1) {
                    if (parseInt(monthC) > 1) {
                        result = "" + parseInt(monthC) + " months ago"
                    } else {
                        result = "" + parseInt(monthC) + " month ago"
                    }
                } else if (weekC >= 1) {
                    if (parseInt(weekC) > 1) {
                        result = "" + parseInt(weekC) + " weeks ago"
                    } else {
                        result = "" + parseInt(weekC) + " week ago"
                    }
                } else if (dayC >= 1) {
                    if (parseInt(dayC) > 1) {
                        result = "" + parseInt(dayC) + " days ago"
                    } else {
                        result = "" + parseInt(dayC) + " day ago"
                    }
                } else if (hourC >= 1) {
                    if (parseInt(hourC) > 1) {
                        result = "" + parseInt(hourC) + " hours ago"
                    } else {
                        result = "" + parseInt(hourC) + " hour ago"
                    }
                } else if (minC >= 1) {
                    if (parseInt(minC) > 1) {
                        result = "" + parseInt(minC) + " minutes ago"
                    } else {
                        result = "" + parseInt(minC) + " minute ago"
                    }
                }
                return result;
            },
            getWidthAndHeight(e, i) {
                let img = new Image();
                img.src = e.cover
                img.onload = () => {
                    // let str = 'width: ' + img.width + ' ; ' + 'height: ' + img.height + ' ; ' + 'loaded'
                    // console.log(str, 'str')
                    if (img.width > 0 || img.height > 0) {
                        let obj = {
                            wth: null
                        }
                        if (Number(img.width) > Number(img.height)) {
                            obj.wth = 1
                        } else {
                            obj.wth = 0
                        }
                        Object.assign(this.tableData[i], obj)
                    }
                };

            },
            getList(pageNum) {
                if (pageNum == 1) {
                    this.pageData.pageNum = 1;
                }

                let searchForm = {};
                searchForm.sort = 'create_datetime desc'
                searchForm.pageNum = this.pageData.pageNum
                searchForm.pageSize = this.pageData.pageSize
                let params = Qs.stringify(searchForm, {arrayFormat: 'repeat'})
                getUserSaveList(params).then((res) => {
                    if (res.data.errorID == 0) {
                        // this.tableData = res.data.object.list || []
                        // wth判断列表图片宽高 start
                        let data_list = res.data.object.list || []
                        let dataList = []
                        let obj = {
                            wth: null
                        }
                        for (let i = 0; i < data_list.length; i++) {
                            if (data_list[i].status == 1) {
                                Object.assign(data_list[i], obj)
                                dataList.push(data_list[i])
                            }
                        }
                        // wth判断列表图片宽高 start
                        // // 刷新列表 or 加载更多
                        if (pageNum == 1) {
                            window.scrollTo(0, 0)
                            // this.tableData = res.data.object.list || []
                            this.tableData = dataList
                        } else {
                            // this.tableData = this.tableData.concat(res.data.object.list)
                            this.tableData = this.tableData.concat(dataList)
                        }
                        // // 分页信息配置
                        this.pageInfo.totalPages = res.data.object.pages
                        this.pageInfo.totalCount = res.data.object.total
                        this.pageData.pageNum = this.pageData.pageNum + 1
                        if (this.pageData.pageNum > this.pageInfo.totalPages) {
                            this.finished = true
                        }
                        // 要求共显示十行：每行两个，总共20个，每次请求十个，最多两次结束请求
                        if (this.pageData.pageNum > 2) {
                            this.finished = true
                        }
                        this.loading = false
                    } else {
                        this.$toast(res.data.message)
                        this.finished = true
                        this.loading = false
                    }

                }).catch((e) => {
                    console.log(e)
                    this.$toast('error, please try again later~')
                    this.finished = true
                    this.loading = false
                })
            },
            onClickDelete() {
                console.log(this.deleteSubmit)
                let submitForm = {};
                submitForm.ids = this.deleteSubmit;
                let params = Qs.stringify(submitForm, {arrayFormat: 'repeat'})
                // return false
                deleteFavourite(params).then((res) => {
                    if (res.data.errorID == 0) {
                        this.deleteSelected = false
                        this.getList(1)
                    } else {
                        this.$toast(res.data.message)
                    }

                }).catch((e) => {
                    console.log(e)
                    this.$toast('error, please try again later~')
                })
            }
        }
    }
</script>

<style>
    .page-favourites .van-nav-bar{
        background-color: #FF9900;
        z-index: 9;
    }
    .page-favourites .van-nav-bar .van-icon{
        color: #fff;
        margin-right: 15px;
        font-size: 18px;
    }
    .page-favourites  .van-list__loading{
        width: 100%;
        /*border-top: 1px solid #F2F2F2;*/
    }
    .favourites .van-checkbox-group{
        width: 100%;
    }
    .favourites .main-explore .explore-item .f-group-check.van-cell{
        position: absolute;
        top: 21px;
        left: 18px;
        /*z-index: 1;*/
        padding: 0;
        background: transparent;
        width: auto;
    }
    .favourites .main-explore .van-checkbox__icon .van-icon{
        background: rgba(255,255,255,0.2);
    }
    .favourites .main-explore .van-checkbox__icon--checked .van-icon{
        background-color: #06bf04;
    }
    .favourites .main-explore .van-hairline--top-bottom:after{
        border-width: 0;
    }
</style>
<style scoped>
    .main-explore, .f-group{
        position: relative;
        background: #fff;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        text-align:center;
        flex-wrap: wrap;
        padding-right: 4%;
    }
    .main-explore {
        padding: 0;
        margin: 46px 0 50px;
    }
    .main-explore .explore-item{
        display: block;
        padding: 14px 0 0;
        margin-left: 4%;
        width: 46%;
        text-decoration: none;
        color: #000;
        /*margin-right: 8%;*/
        /*border-bottom: 1px solid #F2F2F2;*/
        position: relative;

    }
    .main-explore .explore-item.one:nth-last-child(2), .main-explore .explore-item.two:nth-last-child(2){
        border-bottom: none;
    }
    .main-explore .explore-item.two:nth-last-child(3){
        border-bottom: none;
    }
    .main-explore .explore-item:nth-child(2n){
        margin-right: 0;
    }

    .main-explore .explore-item .explore-item-icon{
        width: 100%;
        /*height: 135px;*/
        /*margin: 0 auto 5px;*/
        /*border: 1px solid #eee;*/
        align-items: center;
        display: flex;
        background: #f0f0f0;
        position: relative;
        z-index: 0;
        height: 0;
        padding: 0 0 100%;
        overflow: hidden;
        border-radius: 6px;
    }
    .main-explore .explore-item .explore-item-icon::before{
        content: "Tolymoly";
        position: absolute;
        top: 50%;
        bottom: 0;
        right: 0;
        left: 0;
        text-align: center;
        background: #f0f0f0;
        font-size: 1.5rem;
        font-weight: 700;
        color: #c0bfbf;
        /*line-height: 135px;*/
        z-index: -1;
        margin-top: -12px;
    }
    .main-explore .explore-item > *{
        display: block;
        margin: 0 auto;
    }
    .main-explore .explore-item-icon img {
        /*max-width:100%;*/
        /*max-height:100%;*/
        /*display: block;*/
        /*margin: 0 auto;*/
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 1;
        width: 100%;
    }
    .main-explore .explore-item-icon img.width-max{
        width: auto;
        left: 50%;
        right: auto;
        height: 100%;
        transform: translate(-50%);
    }
    .main-explore .explore-item-icon img.height-max{
        top: 50%;
        transform: translateY(-50%);
    }
    .main-explore .explore-item .explore-item-label{
        /*color: inherit;*/
        font-size: 14px;
        line-height: 160%;
        margin-top: 4px;
        text-align: left;
        overflow: hidden;
        white-space: nowrap;
        text-overflow:ellipsis;

        /*font-size: 12px;*/
        /*font-family: Bitter,sans-serif;*/
        color: #000;
    }
    .main-explore .explore-item .explore-item-label.price{
        /*color: #DB3743;*/
        /*font-size: 16px;*/
        /*font-weight: 600;*/
        font-size: 12px;
        color: #4c4c4c;
    }
    .main-explore .explore-item .explore-item-label.dates{
        color: #A1A1A1;
    }
    .delete-btn{
        z-index: 9;
    }
    .f-like{
        position: absolute;
        top: 22px;
        right: 8px;
        font-size: 22px;
        color: #db3743!important;
    }
    .favourites .none img{
        display: block;
        margin: 0 auto;
    }
    .favourites .none p{
        margin: 0;
        text-align: center;
    }
    .sold-status{
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 9;
        font-size: 18px;
        padding: 4px 0;
        color: #fff;
        background: #DE4B56;
    }
    @media (max-width:375px) and (min-width:321px) {
        .main-explore .explore-item .explore-item-icon{
            /*height: 155px;*/
        }
        .main-explore .explore-item .explore-item-icon::before{
            /*line-height: 155px;*/
        }
    }
    @media (max-width:1080px) and (min-width:376px) {
        .main-explore .explore-item .explore-item-icon{
            /*height: 173px;*/
        }
        .main-explore .explore-item .explore-item-icon::before{
            /*line-height: 173px;*/
        }
    }
</style>
